#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
物业保洁系统文档生成器
将Markdown格式的用户手册和设计文档转换为Word格式
"""

import os
import sys
from datetime import datetime
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
from docx.enum.style import WD_STYLE_TYPE
from docx.oxml.ns import qn
import re

class DocumentGenerator:
    def __init__(self):
        self.doc = Document()
        self.setup_document()
    
    def setup_document(self):
        """设置文档基本格式"""
        # 设置页面边距
        sections = self.doc.sections
        for section in sections:
            section.top_margin = Inches(1)
            section.bottom_margin = Inches(1)
            section.left_margin = Inches(1)
            section.right_margin = Inches(1)
        
        # 设置中文字体
        self.doc.styles['Normal'].font.name = '宋体'
        self.doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
        self.doc.styles['Normal'].font.size = Pt(12)
        
        # 设置标题样式
        title_style = self.doc.styles.add_style('CustomTitle', WD_STYLE_TYPE.PARAGRAPH)
        title_style.font.name = '黑体'
        title_style.font.size = Pt(18)
        title_style.font.bold = True
        title_style.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        
        # 设置一级标题样式
        heading1_style = self.doc.styles.add_style('CustomHeading1', WD_STYLE_TYPE.PARAGRAPH)
        heading1_style.font.name = '黑体'
        heading1_style.font.size = Pt(16)
        heading1_style.font.bold = True
        heading1_style.paragraph_format.space_before = Pt(12)
        heading1_style.paragraph_format.space_after = Pt(6)
        
        # 设置二级标题样式
        heading2_style = self.doc.styles.add_style('CustomHeading2', WD_STYLE_TYPE.PARAGRAPH)
        heading2_style.font.name = '黑体'
        heading2_style.font.size = Pt(14)
        heading2_style.font.bold = True
        heading2_style.paragraph_format.space_before = Pt(6)
        heading2_style.paragraph_format.space_after = Pt(3)
        
        # 设置三级标题样式
        heading3_style = self.doc.styles.add_style('CustomHeading3', WD_STYLE_TYPE.PARAGRAPH)
        heading3_style.font.name = '黑体'
        heading3_style.font.size = Pt(13)
        heading3_style.font.bold = True
        heading3_style.paragraph_format.space_before = Pt(3)
        heading3_style.paragraph_format.space_after = Pt(3)
    
    def add_title(self, title):
        """添加文档标题"""
        p = self.doc.add_paragraph(title, style='CustomTitle')
        self.doc.add_paragraph()
    
    def add_heading(self, text, level=1):
        """添加标题"""
        style_map = {
            1: 'CustomHeading1',
            2: 'CustomHeading2',
            3: 'CustomHeading3'
        }
        style = style_map.get(level, 'CustomHeading1')
        self.doc.add_paragraph(text, style=style)
    
    def add_paragraph(self, text):
        """添加段落"""
        self.doc.add_paragraph(text)
    
    def add_code_block(self, code, language=None):
        """添加代码块"""
        p = self.doc.add_paragraph()
        p.style.font.name = 'Consolas'
        p.style.font.size = Pt(10)
        p.style.paragraph_format.left_indent = Inches(0.5)
        p.style.paragraph_format.space_after = Pt(6)
        
        # 设置代码背景色
        run = p.add_run(code)
        run.font.color.rgb = RGBColor(0, 0, 139)
    
    def add_table(self, headers, rows):
        """添加表格"""
        table = self.doc.add_table(rows=len(rows)+1, cols=len(headers))
        table.style = 'Light Shading Accent 1'
        
        # 设置表头
        for i, header in enumerate(headers):
            cell = table.cell(0, i)
            cell.text = header
            cell.paragraphs[0].runs[0].font.bold = True
            cell.paragraphs[0].runs[0].font.color.rgb = RGBColor(255, 255, 255)
        
        # 设置数据行
        for i, row in enumerate(rows):
            for j, cell_data in enumerate(row):
                table.cell(i+1, j).text = str(cell_data)
    
    def add_page_break(self):
        """添加分页符"""
        self.doc.add_page_break()
    
    def parse_markdown(self, content):
        """解析Markdown内容"""
        lines = content.split('\n')
        in_code_block = False
        code_buffer = []
        
        for line in lines:
            line = line.strip()
            
            # 处理代码块
            if line.startswith('```'):
                if in_code_block:
                    # 结束代码块
                    self.add_code_block('\n'.join(code_buffer))
                    code_buffer = []
                    in_code_block = False
                else:
                    # 开始代码块
                    in_code_block = True
                    language = line[3:].strip()
                continue
            
            if in_code_block:
                code_buffer.append(line)
                continue
            
            # 处理标题
            if line.startswith('# '):
                self.add_heading(line[2:], level=1)
            elif line.startswith('## '):
                self.add_heading(line[3:], level=2)
            elif line.startswith('### '):
                self.add_heading(line[4:], level=3)
            elif line.startswith('#### '):
                self.add_heading(line[5:], level=3)
            
            # 处理表格
            elif line.startswith('|') and '|' in line:
                # 简单的表格处理，实际使用时需要更复杂的解析
                pass
            
            # 处理列表
            elif line.startswith('- ') or line.startswith('* '):
                self.add_paragraph('  • ' + line[2:])
            
            # 处理普通段落
            elif line and not line.startswith('```'):
                self.add_paragraph(line)
    
    def save(self, filename):
        """保存文档"""
        self.doc.save(filename)
        print(f"文档已保存: {filename}")

def read_markdown_file(filepath):
    """读取Markdown文件"""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            return f.read()
    except FileNotFoundError:
        print(f"文件未找到: {filepath}")
        return None

def generate_document(title, md_file, output_file):
    """生成Word文档"""
    print(f"正在生成 {title}...")
    
    # 读取Markdown内容
    content = read_markdown_file(md_file)
    if not content:
        return False
    
    try:
        # 创建文档生成器
        generator = DocumentGenerator()
        
        # 添加文档信息
        generator.doc.add_paragraph(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        generator.doc.add_paragraph(f"文档版本: v1.0")
        generator.doc.add_paragraph()
        
        # 添加标题和内容
        generator.add_title(title)
        generator.parse_markdown(content)
        
        # 保存文档
        generator.save(output_file)
        print(f"✓ 成功生成: {output_file}")
        return True
    except Exception as e:
        print(f"✗ 生成失败 {title}: {str(e)}")
        return False

def find_markdown_files(directory="."):
    """查找目录下所有的Markdown文件"""
    markdown_files = []
    for root, dirs, files in os.walk(directory):
        # 跳过node_modules等目录
        dirs[:] = [d for d in dirs if not d.startswith('.') and d not in ['node_modules', '__pycache__', 'target', 'dist']]
        
        for file in files:
            if file.endswith('.md'):
                filepath = os.path.join(root, file)
                filename_without_ext = os.path.splitext(file)[0]
                # 输出文件放在与源文件相同目录
                output_path = os.path.join(root, f"{filename_without_ext}.docx")
                markdown_files.append({
                    'filepath': filepath,
                    'filename': file,
                    'title': filename_without_ext,
                    'output': output_path
                })
    return markdown_files

def generate_all_markdown_files(directory=".", specific_files=None):
    """生成指定目录下所有Markdown文件的Word文档"""
    print(f"扫描目录: {os.path.abspath(directory)}")
    
    if specific_files:
        # 如果指定了特定文件
        files_to_process = []
        for file_path in specific_files:
            if os.path.exists(file_path) and file_path.endswith('.md'):
                filename = os.path.basename(file_path)
                title = os.path.splitext(filename)[0]
                # 输出文件放在与源文件相同目录
                output = os.path.join(os.path.dirname(file_path), f"{title}.docx")
                files_to_process.append({
                    'filepath': file_path,
                    'filename': filename,
                    'title': title,
                    'output': output
                })
            else:
                print(f"文件不存在或不是Markdown: {file_path}")
    else:
        # 自动查找所有Markdown文件
        files_to_process = find_markdown_files(directory)
    
    if not files_to_process:
        print("未找到任何Markdown文件")
        return
    
    print(f"找到 {len(files_to_process)} 个Markdown文件")
    
    success_count = 0
    failed_count = 0
    
    for file_info in files_to_process:
        print(f"\n处理文件: {file_info['filename']}")
        
        if generate_document(
            file_info['title'],
            file_info['filepath'],
            file_info['output']
        ):
            success_count += 1
        else:
            failed_count += 1
    
    print(f"\n转换完成统计:")
    print(f"成功: {success_count} 个文件")
    print(f"失败: {failed_count} 个文件")
    print(f"总计: {len(files_to_process)} 个文件")

def print_usage():
    """打印使用说明"""
    print("""
物业保洁系统Markdown转Word文档工具

使用方法:
    python generate_docs.py                    # 转换当前目录下所有.md文件
    python generate_docs.py [目录路径]         # 转换指定目录下所有.md文件
    python generate_docs.py file1.md file2.md  # 转换指定的.md文件

示例:
    python generate_docs.py                    # 转换当前目录
    python generate_docs.py ./docs             # 转换./docs目录
    python generate_docs.py README.md          # 转换单个文件
    python generate_docs.py *.md               # 转换所有.md文件
    
注意事项:
    - 需要安装python-docx: pip install python-docx
    - 支持中文内容
    - 自动跳过node_modules、__pycache__等目录
    - 生成的Word文件与原Markdown文件同名
""")

def main():
    """主函数"""
    print("物业保洁系统Markdown转Word文档工具")
    print("=" * 50)
    
    # 检查参数
    if len(sys.argv) > 1 and (sys.argv[1] == '-h' or sys.argv[1] == '--help'):
        print_usage()
        return
    
    # 检查python-docx是否安装
    try:
        from docx import Document
    except ImportError:
        print("错误: 未安装python-docx库")
        print("请运行: pip install python-docx")
        return
    
    # 处理命令行参数
    if len(sys.argv) == 1:
        # 无参数，转换当前目录
        generate_all_markdown_files()
    elif len(sys.argv) == 2 and os.path.isdir(sys.argv[1]):
        # 指定目录
        generate_all_markdown_files(sys.argv[1])
    else:
        # 指定文件列表
        generate_all_markdown_files(specific_files=sys.argv[1:])

if __name__ == "__main__":
    main()